from pymongo import MongoClient
from pymongo import InsertOne, DeleteOne,UpdateMany
client = MongoClient("127.0.0.1:27017")
db = client.get_database("test")
#1，批量写入
requests = [
    InsertOne({"name": "apple", "color": "red", "qty": 10}),
    InsertOne({"name": "apple", "color": "red", "qty": 10}),
    DeleteOne({"name":  "banana"}),
    UpdateMany({"name":"apple"},{"$pop":{"varieties ":-1}}, upsert=True)]
result = db.fruitshop.bulk_write(requests)
print('result:', result.acknowledged)
print('InsertOne result:', result.inserted_count)
print('DeleteOne result:', result.deleted_count)
print('UpdateMany result:', result.modified_count)
#2，聚合
result= db.fruitshop.aggregate([{'$group': {'_id': "$name", 'num': {'$sum':"$qtr"}}}])
for i in result:
    print(i)
#3.聚合2
pipe1 = {"$match": {"name": "apple"}}
pipe2 = {'$group': {'_id': "$name", 'num': {'$sum':"$qtr"}}}
result = db.fruitshop.aggregate([pipe1,pipe2])
#4，索引
db.fruitshop.drop_indexes() #删除所有索引
db.fruitshop.create_index("name")
db.fruitshop.create_index([("name",1), ("tags",1)],name= "index_1")
db.fruitshop.drop_indexes() #删除所有索引

db.client.close()